package com.xfsg.core.log;

import com.xfsg.core.log.config.AliyunLogItem;
import com.xfsg.core.log.config.AliyunLogProperties;
import com.xfsg.core.log.enhancer.LogEnhancer;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;


/**
 * @Classname LogAppenderRegister
 * @Description com.xfsg.core.log appender 注册
 * @date 2021/12/14 15:25
 * @author ZhangYi
 */
@NoArgsConstructor
public class LogAppenderRegister implements EnvironmentAware {

	public static final String ENV_DEV = "dev";

	@Resource
	private AliyunLogProperties aliyunLogProperties;
	@Resource
	private AliyunLogItem aliyunLogItem;


	private static final Logger logger = LoggerFactory.getLogger(LogAppenderRegister.class);
	@Override
	public void setEnvironment(Environment environment) {

		logger.info("pitaya aliyun appender has been integrated into system");

		ConfigurableEnvironment env = (ConfigurableEnvironment)environment;

		// init logEnhancer
		ClassLoader classLoader = env.getClass().getClassLoader();
		LogEnhancerBinder.bindClassLoader(classLoader);
		LogEnhancer logEnhancer = LogEnhancerBinder.getInstance();

		if (null == aliyunLogProperties.getProject().getName() || "".equals(aliyunLogProperties.getProject().getName())){
			logger.warn("aliyun.log.project.name 未配置");
			logger.info("pitaya aliyun appender has been fail initialized");
			return;
		}

		if (aliyunLogProperties.getProject().getName().endsWith(ENV_DEV)){
			logger.warn("开发环境pitaya aliyun log 不启动");
			logger.info("pitaya aliyun appender has been canceled initialized");
			return;
		}

		// do nothing if aliyun appender has been bound
		if(!logEnhancer.alreadyBound()) {
			logEnhancer.enhance(aliyunLogProperties,aliyunLogItem);
			logger.info("pitaya aliyun appender has been successfully initialized");
		}
	}


}
